/**
* @Author: Astadia Ltd.
* @Name: CreateRemoveAssetsForOpportunity
* @Description: This trigger is used to Create or Delete a Asset beased on Opportunity Stage
* <code>Folowing are the Criteria </code>
* <ol>
*	<li>When the previous Stage of Apportunity is Not "Closed -Won" and New Stage is "Closed One", 
		CREATE Assets for all products for that Apportunity </li>
*   <li>When the previous Stage of Apportunity is Closed -Won and New Stage is Not Closed One, 
		DELETE Assets for all products for that Apportunity</li>	
* </0l>
*
**/
trigger CreateRemoveAssetsForOpportunity on Opportunity (after insert, after update) {

	// List of Opportunity for which assets needs to be Created 
	Set<Id> assetsToBeCreated= null;
	
	// List of Opportunity for which assets needs
	Set<Id> assetsToBeDeleted= null;
	
	OpportunityManager oppManager = null;
	
	// Iterating over all Opportunities
	for (Opportunity opportunity : Trigger.new){
		
		System.debug('Inside For Loop Trigger');
		
		assetsToBeCreated= new Set<Id>();
		assetsToBeDeleted= new Set<id>();
		// On Update on Opportunity
		if(Trigger.isUpdate ){
		
	
		System.debug('opportunity.StageName := ' + opportunity.StageName + ' Old Name:= ' + Trigger.oldMap.get(opportunity.id).StageName + 'opportunity.HasOpportunityLineItem:= ' + opportunity.HasOpportunityLineItem );
			//If New opportunity stage is Closed -Won and old stage is NOT Closed won
			if('Closed Won' == opportunity.StageName && 'Closed Won' != Trigger.oldMap.get(opportunity.id).StageName &&  opportunity.HasOpportunityLineItem){
				assetsToBeCreated.add(opportunity.id);
				
			}
			//If New opportunity stage is NOT Closed -Won and old stage is Closed won
			
			else if ('Closed Won' != opportunity.StageName && 'Closed Won' == Trigger.oldMap.get(opportunity.id).StageName &&  opportunity.HasOpportunityLineItem){
				assetsToBeDeleted.add(opportunity.id);
				System.debug('assetsToBeDeleted := ' + opportunity.id);
			}
		}	
			
		//On Insert on Opportunity If New opportunity stage is Closed -Won
		if(Trigger.isInsert && 'Closed Won' == opportunity.StageName && opportunity.HasOpportunityLineItem)
			//create Asset
			assetsToBeCreated.add(opportunity.id);
		}
		

	
	// if List has any record than create assets For the Opportunity(s)
	if(null!= assetsToBeCreated && !assetsToBeCreated.isEmpty() ){
		oppManager = new OpportunityManager();
		System.debug('Calling oppManager.createAssetsForOpportunities');
		oppManager.createAssetsForOpportunities(assetsToBeCreated);
	}
	
	// if List has any record than Deete assets For the Opportunity(s)
	if (null!= assetsToBeDeleted && !assetsToBeDeleted.isEmpty() ){
		oppManager = new OpportunityManager();
		System.debug('Calling oppManager.deleteAssetsForOpportunities');
		oppManager.deleteAssetsForOpportunities(assetsToBeDeleted);
	}
}